package com.bro.person.admin.interceptors;

import com.bro.person.admin.common.CommonUrlControl;
import com.bro.person.admin.service.ISecurityService;
import com.bro.person.admin.struct.SecurityUserStruct;
import com.bro.person.admin.utils.HttpUtils;
import com.bro.person.base.constants.ConstConfig;
import com.bro.person.base.enums.error.GlobalEnum;
import com.bro.person.base.utils.JsonUtil;
import com.bro.person.base.utils.RequestUtil;
import com.bro.person.base.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author swallow
 * Created by swallow on 2018/11/2.<br>
 */
public class AuthorizeInterceptor implements HandlerInterceptor, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(AuthorizeInterceptor.class);

    @Resource
    private ISecurityService securityService;

    @Override
    public void afterPropertiesSet() {
        Assert.notNull(securityService, "securityService can't be null");
    }

    /**
     * 用户操作拦截检查
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取ua
        String userAgent = request.getHeader("User-Agent");
        // 获取requestUri
        String requestUri = request.getRequestURI();
        // 获取remoteIp
        String remoteIp = RequestUtil.getRemoteIP(request);

        logger.debug(
                "[AuthorizeInterceptor][preHandle] entering request:{},response:{},handlerMethod:{},userAgent:{},requestUri:{},remoteIp:{}",
                request, response, handler, userAgent, requestUri, remoteIp);

        // TODO 是否有对应的cookie值 先写死 然后看看名字是什么再放到对应的 接口中 后期需要更改成 cookie设置 暂时使用session
        HttpSession session = request.getSession();
        Object adminUser = session.getAttribute(ConstConfig.SECURITY_USER_SESSION_KEY);
        if (adminUser == null) {
            // 如果不存在 直接跳转到登录界面
            returnLoginView(request,response,GlobalEnum.BRO_USER_LOGIN_EXPIRE);
            return false;
        }
        SecurityUserStruct wyAdminUser = (SecurityUserStruct) adminUser;
        boolean flag = securityService.checkAuthentication(wyAdminUser.getUserId(), requestUri);
        if (!flag) {
            returnLoginView(request,response,GlobalEnum.BRO_UNAUTHORIZED_ERROR);
            return false;
        }
        // 放行
        session.setMaxInactiveInterval(ConstConfig.SECURITY_USER_SESSION_INVALID_TIME);
        return true;
    }

    /**
     * 返回对应的界面或者json
     *
     */
    private void returnLoginView(HttpServletRequest request, HttpServletResponse response, GlobalEnum globalEnum) {
        try {
            //非ajax请求 直接让用户跳转页面
            if(!HttpUtils.isAjaxRequest(request)){
                response.sendRedirect(CommonUrlControl.LOGIN_REDIRECT_URL);
                return;
            }
            //如果用户是ajax请求
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out;
    //            JsonResultBean jsonResultBean = new JsonResultBean(JsonResultBean.RESULT_FAILED, "/login", 0, "返回登录页面");
            ResultVO resultVO = new ResultVO(globalEnum);
            out = response.getWriter();
            String jsonResultBeanString = JsonUtil.gson.toJson(resultVO);
    //            String jsonResultBeanString = "请登录";
            out.write(jsonResultBeanString);
        } catch (Exception e) {
            logger.error("[AuthorizeInterceptor][returnLoginView] errordesc response:{},e:{}", response, e);
            try {
                response.sendError(500);
            } catch (IOException e1) {
                logger.error("[AuthorizeInterceptor][returnLoginView] errordesc response:{}, e1:{}", response,
                        e1.getMessage());
            }
        }
    }

    /**
     * 执行结束
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        logger.debug("[AuthorizeInterceptor][postHandle] entering request:{},response:{},handler:{},modelAndView:{}",
                request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
